
#100w条topic匹配一条topic时间0s   在20g内存2g cpu上

import time


import random
set_=set()
def generate_random_string(length=10):
    """生成随机字符串"""
    res=''
    for i in range(length):
        res+=str(random.randint(0,9))
    return res


def generate_secure_random_string(length=5):
    global set_
    while 1:
        """生成安全的随机字符串"""
        letters1 = generate_random_string()+'#' # 包含大小写字母和数字
        # print(letters1)
        if letters1+'#' not in set_:
            set_.add(letters1)
            break
    while 1:
        """生成安全的随机字符串"""
        letters2 = generate_random_string()  # 包含大小写字母和数字
        # print(letters2)
        if letters2 not in set_:
            set_.add(letters2)
            break
    # print(letters1,letters2)
    return letters1,letters2
def find_topic(topic):
    match_topic=''
    now_topic=topics
    for i in topic:
        # print('find',i,topics)
        if '#'in now_topic:
            return {"match_topic":match_topic+'#',"info":now_topic['#']['value']}
        else:
            match_topic+=i
            now_topic=now_topic.get(i)
            if now_topic is None:return#没有匹配到
    if now_topic.get('value') is True:return {"match_topic":match_topic,"info":now_topic['value']}
    elif now_topic.get('#')is not None:return {"match_topic":match_topic+'#',"info":now_topic['#']['value']}
    else:return None#没有匹配到
topics={}
def add_topics(topic,info={}):
    global topics
    new_topics=topics
    for i in topic:
        new_topics2=new_topics.get(i)
        if new_topics2 is None:
            new_topics[i]={}
            new_topics=new_topics[i]
        else:
            new_topics=new_topics2
    new_topics['value']=info
t1=time.time()
find_lst=[]
for i in range(1000):
    topic1,topic2 = generate_secure_random_string(15)
    add_topics(topic1)
    add_topics(topic2)
    find_lst.extend([topic1,topic2])
    if i%10000==0:print(i)
t2=time.time()
print("生成时间:",t2-t1)
add_topics("fdsadfefasdfarewrwqe#",{"id":(1,2,3),"callback":"dsafaf"})
# for v in find_lst:
#     t1=time.time()
#     handlers = find_topic(v)
#     print("要搜索的值:",v)
#     print("搜索到的值:",handlers)
#     t2=time.time()
#     print("单次搜索时间",t2-t1,v)
# print()

# print()

# print()

# print()
t1=time.time()
# for i in range(109):
v="fdsadfefasdfarewrwqe"
handlers = find_topic(v)
print("要搜索的值:",v)
print("搜索到的值:",handlers)
t2=time.time()
print("单次搜索时间",t2-t1,v)
t1=t2


# print()
t1=time.time()
# for i in range(109):
v="fdsadfefasdfarewrwqerrr"
handlers = find_topic(v)
print("要搜索的值:",v)
print("搜索到的值:",handlers)
t2=time.time()
print("单次搜索时间",t2-t1,v)
t1=t2
# print()
t1=time.time()
# for i in range(109):
v="fdsadfefasdfarewr"
handlers = find_topic(v)
print("要搜索的值:",v)
print("搜索到的值:",handlers)
t2=time.time()
print("单次搜索时间",t2-t1,v)
t1=t2